package dao;

import bean.userBean;
import util.JSON;
import util.Md5;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class userDao {
    Db db = new Db();											//新建实例（该实例实现了数据的增删改查）
    String sql = "";
    ResultSet rs = null;

    public HashMap<String , Integer> queryBookSelf(HttpServletRequest request) throws SQLException {
        HttpSession session = request.getSession();
        userBean user= (userBean) session.getAttribute("user");
        String msg = "";
        if(user==null){     //无登录
            System.out.println("无登录访问");
            return null;
        }else{
            System.out.println("已登录："+user.getUserName());
            sql="select userBookSelf from tb_user where userNumber=?";
            rs=db.select(sql, user.getUserNumber());
            if (rs == null) {
                msg += "数据库操作发生错误！";
                return null;
            }

            if (rs.next() == false) {
                db.close();
                return null;
            }
            String userBookSelfJSON=null;
            HashMap<String , Integer> map=null;
            userBookSelfJSON=rs.getString("userBookSelf");
            System.out.println("已查询出："+userBookSelfJSON);
            try{
                map= JSON.jsonToHashMap(userBookSelfJSON);
                System.out.println("已转化为bookSelf:"+map);
            }catch (Exception e){
                System.out.println("bookSelf is null");
            }finally {
                db.close();
                return map;
            }

        }
    }
    /**------------------------------ 新添记录 */
    public String insert (HttpServletRequest request, userBean user) {

        String userNumber = "0";
        String msg = "";

        try {
            String username, password,  role;

            username	= user.getUserName();
            password 	= user.getPassword();
            role 		= user.getUserType();

            String salt = "login_fdsfj45349fd";							//加点料（盐）。此料应与登录验证LoginCheck.java中加的料相同
            password = Md5.getMd5(username + password + salt);			//对用户名+密码+料进行MD5加密

            sql = "insert tb_user (userName, password,  userType)"
                    + " values (?, ?, ?)";
            userNumber = db.insert(sql, username, password, role);

            if (userNumber.equals("0")) {
                //msg += "用户新添失败！";
                return userNumber;
            }

            //msg = "用户新添成功！";
            return userNumber;

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);
        }

        return userNumber;
    }

}
